/*
 * @Author: 郭桓
 * @Date: 2019-02-18 10:27:44
 * @LastEditors: GuoHuan
 * @LastEditTime: 2019-03-08 15:32:01
 * @Description: file content
 */
// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const Utils = require('Utils');
cc.Class({
    extends: cc.Component,

    properties: {
        bgImg: cc.Node,
        goodsItem: cc.Prefab,
        checkItem: cc.Prefab, //订单列表
        selectNode: cc.Node,
        list: cc.Node,
        checkList: cc.ScrollView,
        imgBanner: cc.PageView,
        topMenu: cc.Node,
        bottomMenu: cc.Node,
        noteActiviy: cc.Node,
        noticeNode: cc.Node,
        moreNode: cc.Node,
        lbName: cc.Label,
        loadingNode: cc.Node,
        inputPhone: cc.EditBox, //手机号
        inputCode: cc.EditBox, //验证码
        btnCode: cc.Button, //获取验证码
        registerNode: cc.Node,
        winNode: cc.Node,
        stateGroup: {
            default: [],
            type: cc.SpriteFrame
        },
        menuGroup: {
            default: [],
            type: cc.Node
        },
        _exchangegood: null,
        _pirseType: 1, //默认是一
        _selectIdx: -1,
        _goodsdata: null,
        _updateOrderTime: 0,
    },


    loginOver(data) {
        this.registerNode.active = false;
        Utils.singleton.userinfo = data.result;
        Utils.singleton.userinfo.loginId = data.loginId;



        cc.sys.localStorage.setItem("usrinfo", JSON.stringify(Utils.singleton.userinfo)); //账号凭证  
        this.moreNode.getChildByName('gold').getComponent(cc.Label).string = Utils.singleton.userinfo.gold;
        this.moreNode.getChildByName('point').getComponent(cc.Label).string = Utils.singleton.userinfo.score;
        this.moreNode.getChildByName('nums').getComponent(cc.Label).string = Utils.singleton.userinfo.scout;
        Utils.singleton.loadingNode.getChildByName('shop').getChildByName('gold').getComponent(cc.Label).string = Utils.singleton.userinfo.gold;
        if (this.isPoneAvailable(Utils.singleton.userinfo.account)) {
            this.inputPhone.string = Utils.singleton.userinfo.account;
            this.winNode.getChildByName('win_address').getChildByName('phone').getChildByName('input_code').getChildByName('box').getComponent(cc.EditBox).string = Utils.singleton.userinfo.account;
            this.lbName.string = Utils.singleton.userinfo.account;
        } else {
            this.lbName.string = '游客' + Utils.singleton.userinfo.account.substr(Utils.singleton.userinfo.account.length - 6);
        }
    },


    updateGold() {
        this.moreNode.getChildByName('gold').getComponent(cc.Label).string = Utils.singleton.userinfo.gold;
        this.moreNode.getChildByName('point').getComponent(cc.Label).string = Utils.singleton.userinfo.score;
        Utils.singleton.loadingNode.getChildByName('shop').getChildByName('gold').getComponent(cc.Label).string = Utils.singleton.userinfo.gold;
    },

    /**
     * 兑换口红
     * @param {*} info 
     */
    changeKH(info) {
        if (info == null)
            return;
        this._exchangegood = null;
        if (typeof info == 'number') {
            for (let i = 0; i < this._goodsdata.length; i++) {
                if (this._goodsdata[i].id == info) {
                    this._exchangegood = this._goodsdata[i];
                }
            }
            if (this._exchangegood == null) {
                return;
            }
        } else {
            this._exchangegood = info;
        }
        this.winNode.active = true;
        this.winNode.getChildByName('win_check').active = false;
        this.winNode.getChildByName('win_kf').active = false;
        this.winNode.getChildByName('win_address').active = true;
    },


    onLoad() {
        this.winNode.active = false;
        this._pirseType = 1;
        this.noteActiviy.active = false;
        this.moreNode.active = false;
        this.registerNode.active = false;

        if (Utils.singleton == null) {
            Utils.singleton = new Utils.Utils();
        }

        if (Utils.singleton.loadingNode == null)
            Utils.singleton.setLoadingNode(this.loadingNode);


        Utils.singleton.loadingNode.getComponent('AppStart').setButton(this.node.getChildByName('icon_music'));


        Utils.singleton.startLogin(function(err, data) {
            if (err == null) {
                this.loginOver(data);
            }
        }.bind(this), false);


        Utils.singleton.getGoodsList(function(data) {
            cc.log(JSON.stringify(data));
            this._goodsdata = data;
            this.updateList();
        }.bind(this), false);



        var sceneHeight = cc.director.getWinSize().height;
        this.list.height = Math.ceil(sceneHeight - 380 - 160)
        this.list.getChildByName('view').height = this.list.height;
        cc.view.setResizeCallback(function() {
            this.list.height = Math.ceil(cc.director.getWinSize().height - 380 - 160)
            this.list.getChildByName('view').height = this.list.height;
        }.bind(this));



        this.moreNode.getChildByName('gold').getComponent(cc.Label).string = 100;
        this.moreNode.getChildByName('point').getComponent(cc.Label).string = 99;
        this.moreNode.getChildByName('nums').getComponent(cc.Label).string = 98;


        this.imgBanner.node.runAction(cc.repeatForever(cc.sequence(cc.delayTime(10), cc.callFunc(function() {
            let count = this.imgBanner.getPages().length;
            let index = this.imgBanner.getCurrentPageIndex();
            index = ((index < count) && (index + 1 !== count)) ? (index + 1) : 0;
            this.imgBanner.scrollToPage(index, 2);
        }.bind(this), this))));
    },


    updateNotice(list) {
        if (list == null || list.length == 0)
            return;
        let notice = this.noticeNode.getComponent('LoopNotice');
        notice.startLoopNotce(list);
        notice.startLoop();
    },


    start() {
        cc.director.getCollisionManager().enabled = false;
        this.updateNotice(Utils.singleton.noticeList);
        // var item = 
        // this.topMenu.getChildByName('chk_jb').getComponent(cc.Toggle).check();
        // this.topMenu.getChildByName('chk_jifen').getComponent(cc.Toggle).uncheck();
        // let notice = this.noticeNode.getComponent('LoopNotice');
        // notice.startLoopNotce(this._noticeList);
        // notice.startLoop();

        if (Utils.singleton.userinfo.gold != null) {
            this.moreNode.getChildByName('gold').getComponent(cc.Label).string = Utils.singleton.userinfo.gold;
            this.moreNode.getChildByName('point').getComponent(cc.Label).string = Utils.singleton.userinfo.score;
            this.moreNode.getChildByName('nums').getComponent(cc.Label).string = Utils.singleton.userinfo.scout;
            Utils.singleton.loadingNode.getChildByName('shop').getChildByName('gold').getComponent(cc.Label).string = Utils.singleton.userinfo.gold;
        }
    },



    updateItem(node, data, isNew) {
        let img = node.getChildByName('img').getChildByName('img_kh1'); //图片
        let color = node.getChildByName('lb_color').getComponent(cc.Label); //白色的颜色信息
        let costpay = node.getChildByName('cost').getComponent(cc.Label); //价格
        let info = node.getChildByName('lb_info').getComponent(cc.Label);
        let prize = node.getChildByName('lb_prize').getComponent(cc.Label); //价格
        // cc.log("data = " + JSON.stringify(data));
        if (isNew) {
            node.getChildByName('icon_tip').active = false;
            if (data.imgUrl != null) {
                cc.loader.load({
                    url: data.imgUrl,
                    type: 'png'
                }, function(err, texture) {
                    var sprite = new cc.SpriteFrame(texture);
                    this.getComponent(cc.Sprite).spriteFrame = sprite;
                }.bind(img));
            }
            color.string = data.color;
            info.string = data.name;
            prize.string = '专柜价: ' + data.prize + ' 元';

            if (data.preferential == 1) {
                node.getChildByName('icon_tip').active = true;
            }
        }

        if (this._pirseType == 1) { //金币显示
            costpay.string = data.need + '金币\n闯关送';
        } else { //积分显示
            costpay.string = data.score + '\n积分兑换';
        }
    },

    updateCheckList(data) {
        this.checkList.content.removeAllChildren();
        if (data == null || data.length == 0)
            return;
        for (let i = 0; i < data.length; i++) {
            var item = cc.instantiate(this.checkItem);
            this.checkList.content.addChild(item);
            item.getChildByName('time').getComponent(cc.Label).string = data[i].logTime.splice('T')[0];
            item.getChildByName('tel').getComponent(cc.Label).string = data[i].telphone;
            item.getChildByName('name').getComponent(cc.Label).string = data[i].name;
            item.getChildByName('state').getComponent(cc.sprite).spriteFrame = this.stateGroup[data[i].isValid];
        }
    },

    updateList() {
        let list = this.list.getComponent(cc.ScrollView);
        list.content.removeAllChildren();

        for (let i = 0; i < this._goodsdata.length; i++) {
            // cc.log("this._goodsdata = " + JSON.stringify(this._goodsdata[i]));
            var item = cc.instantiate(this.goodsItem);
            list.content.addChild(item);
            this.updateItem(item, this._goodsdata[i], true);
            item.setName(i + '');
            item.on(cc.Node.EventType.TOUCH_END, this.onItemClick, this);
        }
        this.selectGroup(0);
        list.scrollToTop();
    },

    selectGroup(index) {
        if (index == null)
            index = 0;

        if (index == this._selectIdx)
            return;
        this._selectIdx = index;
        let colorNormal = cc.color(140, 38, 48); //new cc.Color(140,38,48)
        for (let i = 0; i < this.menuGroup.length; i++) {
            this.menuGroup[i].getChildByName('icon').color = colorNormal;
            this.menuGroup[i].getChildByName('name').color = colorNormal;
        }

        this.selectNode.x = this.menuGroup[index].x;
        this.menuGroup[index].getChildByName('icon').color = cc.Color.WHITE;
        this.menuGroup[index].getChildByName('name').color = cc.Color.WHITE;
        this.noteActiviy.active = false;
        this.moreNode.active = false;
        this.bottomMenu.getChildByName('bottominfo').active = true;
        if (this._selectIdx == 1) {
            this.noteActiviy.active = true;
            this.bottomMenu.getChildByName('bottominfo').active = false;
        } else if (this._selectIdx == 2) {
            this.moreNode.active = true;
            this.bottomMenu.getChildByName('bottominfo').active = false;
        }
    },

    /**
     * @description: 点击选中
     * @param {type} 
     * @return: 
     */
    onItemClick(sender) {
        let idx = Number.parseInt(sender.target.getName());
        let info = this._goodsdata[idx];
        if (this._pirseType == 1) {
            //闯关  
            if (Utils.singleton.userinfo.gold >= info.need) {
                Utils.singleton.request("canStart", "GET", {
                    needGold: info.need,
                    goodId: info.id,
                    loginVar: Utils.singleton.userinfo.loginId
                }, function(err, data) {
                    if (err == null) {
                        //游戏开始了。将要获取的ID记录下来
                        Utils.singleton.gotoGame(info);
                    }
                }.bind(this));
            } else {
                Utils.singleton.showShop();
            }
        } else {
            if (Utils.singleton.userinfo.score >= info.score) {
                //兑换
                this.changeKH(info)
            } else {
                Utils.singleton.showToast("积分不足，无法兑换");
            }
        }
    },

    /**
     * @description:    checkBox选中
     * @param {type}    
     * @return: 
     */
    onViewCheck(sender, data) {
        console.log("")
        this._pirseType = Number.parseInt(data);
        // let list = this.list.getComponent(cc.ScrollView);
        // list.content.removeAllChildren();
        let list = this.list.getComponent(cc.ScrollView).content;
        for (let i = 0; i < list.childrenCount; i++) {
            let item = list.children[i];
            this.updateItem(item, this._goodsdata[i]);
        }
    },

    isPoneAvailable: function(pone) {
        var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
        if (!myreg.test(pone)) {
            return false;
        } else {
            return true;
        }
    },

    /**
     * @description:   按钮点击
     * @param {type} 
     * @return: 
     */
    onViewClick(sender, data) {
        switch (data) {
            case 'dd': //订单
                {
                    this.winNode.active = true;
                    this.winNode.getChildByName('win_check').active = true;
                    this.winNode.getChildByName('win_kf').active = false;
                    this.winNode.getChildByName('win_address').active = false;
                    
                    let time = new Date().getTime() / 1000;
                    if (time - this._updateOrderTime >= 60 * 10) {
                        //可以更新啦
                        this._updateOrderTime = time;
                        Utils.singleton.request("user/getPrize", "GET", {
                            userId: Utils.singleton.userinfo.id,
                            loginVar: Utils.singleton.userinfo.loginId
                        }, function(err, data) {
                            if (err == null) {
                                this.updateCheckList(data.result);
                            }
                        }.bind(this));
                    }
                }
                break;
            case 'testgame':
                Utils.singleton.testGame();
                break;
            case 'code':
                {

                    if (this.isPoneAvailable(this.inputPhone.string)) {
                        //是手机号
                        cc.log("tel = " + this.inputPhone.string);

                        this.btnCode.interactable = false;
                        this.btnCode.node.runAction(cc.sequence(cc.delayTime(1), cc.callFunc(function() {
                            this.btnCode.interactable = true;
                        }.bind(this), this)));

                        Utils.singleton.request("user/getCode", "GET", {
                            telphone: this.inputPhone.string,
                            from: Utils.singleton.getUrlParam('from')
                        }, function(err, data) {

                        }.bind(this));

                    } else {
                        Utils.singleton.showToast('请输入正确的手机号');
                    }

                }
                break;
            case 'change':
                {
                    this.registerNode.active = true;
                }
                break;
            case 'kf': //客服
            case 'czdwz': //充值未到
            case 'tk': //退kuang
                {
                    this.winNode.active = true;
                    this.winNode.getChildByName('win_check').active = false;
                    this.winNode.getChildByName('win_address').active = false;
                    this.winNode.getChildByName('win_kf').active = true;
                }
                break;
            case 'closeregister':
                {
                    this.registerNode.active = false;
                }
                break;
            case 'closewindow':
                {
                    this.winNode.active = false;
                }
                break;
            case 'login':
                {

                    if (!this.isPoneAvailable(this.inputPhone.string)) {
                        Utils.singleton.showToast('请输入正确的手机号');
                        return;
                    }

                    if (this.inputCode.string.length != 6) {
                        Utils.singleton.showToast('请输入正确的验证码');
                        return;
                    }
                    // {"success":false,"msg":"验证码不存在或者超时"}
                    // this.loginOver()

                    Utils.singleton.request("user/login", "GET", {
                        telphone: this.inputPhone.string,
                        code: this.inputCode.string,
                        from: Utils.singleton.getUrlParam('from')
                    }, function(err, data) {
                        if (err == null) {
                            this.loginOver(data);
                        }
                    }.bind(this));

                }
                break;
            case 'getKH': //获取口红
                {
                    let parent = this.winNode.getChildByName('win_address');
                    let name = parent.getChildByName('name').getChildByName('input_code').getChildByName('box').getComponent(cc.EditBox).string;
                    let phone = parent.getChildByName('phone').getChildByName('input_code').getChildByName('box').getComponent(cc.EditBox).string;
                    let address = parent.getChildByName('address').getChildByName('input_code').getChildByName('box').getComponent(cc.EditBox).string;
                    if (name == '') {
                        Utils.singleton.showToast('请输入联系人');
                        return;
                    }
                    if (!this.isPoneAvailable(phone)) {
                        Utils.singleton.showToast('请输入正确的手机号');
                        return;
                    }
                    if (address == '') {
                        Utils.singleton.showToast('收货地址未设置');
                        return;
                    }

                    Utils.singleton.request("user/insertPrize", "GET", {
                        goodId: this._exchangegood.id,
                        loginVar: Utils.singleton.userinfo.loginId,
                        telPhone: phone,
                        address: address,
                        userName: name
                    }, function(err, data) {
                        if (err == null) {
                            //游戏开始了。将要获取的ID记录下来
                            this._exchangegood = null;
                            this._updateOrderTime = 0;
                            this.winNode.active = false;
                        }
                    }.bind(this));
                }
                break;
        }
    },

    /**
     * @description: 当前显示
     * @param {type} 
     * @return: 
     */
    onMenuClick(sender, data) {
        console.log("data")
        this.selectGroup(Number.parseInt(data));
    }
    // update (dt) {},
});